package com.viewpagertext.fragments;

import android.annotation.SuppressLint;
import android.content.Intent;

import androidx.databinding.DataBindingUtil;

import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.android.material.bottomsheet.BottomSheetDialog;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.viewpagertext.DBHelper.AppDatabase;
import com.viewpagertext.DBHelper.Dao.RecentPlayDao;
import com.viewpagertext.DBHelper.Dao.StarredSongDao;
import com.viewpagertext.Model.DownloadMusic;
import com.viewpagertext.Model.RecentPlay;
import com.viewpagertext.R;
import com.viewpagertext.activitys.SongActivity;
import com.viewpagertext.adapters.ListRecAdapter;
import com.viewpagertext.constructor.ListToPlayEvent;
import com.viewpagertext.constructor.MessageEvent;
import com.viewpagertext.constructor.Song;
import com.viewpagertext.databinding.ActivityMovieDetailBinding;
import com.viewpagertext.json.ListFragmentSongMusics;
import com.viewpagertext.json.StarredSong;
import com.viewpagertext.utils.CommonUtils;
import com.viewpagertext.utils.DownloadMusicUtils;
import com.viewpagertext.utils.FileDownloader;
import com.viewpagertext.utils.HttpUtil;
import com.viewpagertext.utils.SSLSocketClient;
import com.viewpagertext.utils.StatusBarUtil;
import com.viewpagertext.utils.TimeUtil;
import com.viewpagertext.views.MyNestedScrollView;
import com.viewpagertext.views.MyRoundedImageView;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import javazoom.jl.decoder.Bitstream;
import javazoom.jl.decoder.BitstreamException;
import javazoom.jl.decoder.Header;
import jp.wasabeef.glide.transformations.BlurTransformation;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Response;

import static com.viewpagertext.adapters.MusicGridAdapter.FindImgUrlPath;
import static com.viewpagertext.adapters.MusicGridAdapter.FindSongsId;
import static com.viewpagertext.adapters.MusicGridAdapter.MyStarredSong;
import static com.viewpagertext.adapters.MusicGridAdapter.RecentPlayFlag;
import static com.viewpagertext.adapters.MusicGridAdapter.SearchName;
import static com.viewpagertext.adapters.MusicGridAdapter.GroupFlag;


public class ListFragment extends Fragment {
    //通过歌单号去查歌
    StarredSongDao helper = AppDatabase.getInstance().starredSongDao();
    public static List<AsyncTask> tasks = new ArrayList<>();
    RecentPlayDao recentPlayDao = AppDatabase.getInstance().recentPlayDao();
    List<Song> songList;
    public final static String PARAM = "isRecyclerView";
    public static int Max = 30;
    private int imageBgHeight;// 这个是高斯图背景的高度
    private int slidingDistance; // 在多大范围内变色
    private boolean isRecyclerView;
    private ActivityMovieDetailBinding binding;
    private ArrayList<ListFragmentSongMusics.DataBean> mData = new ArrayList<>();
    private ListRecAdapter adapter;
    private ViewPager viewPager;
    private String GetFindSongsId = "https://api.injahow.cn/meting/?type=playlist&id=" + FindSongsId;


    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
            .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
            .build();
    //    https://www.hhlqilongzhu.cn/api/dg_qqmusic.php?gm=%E6%B3%A1%E6%B2%AB&n=1&type=json
//    https://www.hhlqilongzhu.cn/api/dg_mgmusic_24bit.php?msg=%E5%A4%A9%E4%B8%8B&n=4&type=json
    private String FirstPath1 = "https://www.hhlqilongzhu.cn/api/dg_qqmusic.php?gm=";
    private String FirstPath2 = "&n=";
    private String FirstPath3 = "&type=json";
    private String path_612_1 = "https://www.hhlqilongzhu.cn/api/dg_mgmusic_24bit.php?msg=";
    private String LastPath1 =
            "http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=";
    private String LastPath2 = "&type=1&offset=0&total=true&limit=1";
    private String FreeSongPath1 = "http://ovoa.cc/api/QQmusic.php?msg=";
    private String FreeSongPath2 = "&n=1&type=json";
    private String FreeSongPath3 = "&n=";
    private String FreeSongPath4 = "&type=json";
    public static List<Call> clientList = new ArrayList<>();
//    public final static String IMAGE_URL_LARGE ="https://img3.doubanio.com/view/subject/m/public/s4477716.jpg";
//    public final static String IMAGE_URL_MEDIUM ="https://img3.doubanio.com/view/subject/s/public/s4477716.jpg";
//    public final static String IMAGE_URL_SMALL = "https://img3.doubanio.com/view/subject/s/public/s4477716.jpg";


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.activity_movie_detail, container, false);
        EventBus.getDefault().register(this);//注册消息

        if (Objects.requireNonNull(getActivity()).getIntent() != null) {
            isRecyclerView = getActivity().getIntent().getBooleanExtra(PARAM, true);
        }
        viewPager = getActivity().findViewById(R.id.play_viewpager);
        setTitleBar();
        setPicture();
        initSlideShapeTheme();
        setAdapter();// RecyclerView列表显示
        System.out.println("groupflag" + GroupFlag + RecentPlayFlag + MyStarredSong + (SearchName == null));
        if (GroupFlag)
            getGroupSong();
        else if (RecentPlayFlag)
            getRecentSong();
        else if (MyStarredSong)
            getSongsFromDataBase();
        else if (SearchName == null)
            sendRequestWithOkHttp();//请求网络
        else
            sendSearchRequest();//找歌曲
        return binding.getRoot();
    }

    private void getGroupSong() {
        System.out.println("进入group");
    }

    private void getRecentSong() {
        List<RecentPlay> recentPlayList = recentPlayDao.getAllRecentPlay();
        int i = 0;
        Collections.reverse(recentPlayList);
        for (RecentPlay song : recentPlayList) {
            ListFragmentSongMusics.DataBean ld = new ListFragmentSongMusics.DataBean();
            ld.setId(song.songId);
            ld.setLrc(song.lrc);
            ld.setName(song.name);
            ld.setSinger(song.singer);
            ld.setPic(song.pic);
            ld.setUrl(song.path);
            ld.setNumber(String.valueOf(i + 1));
            ld.setTime(song.time);
            mData.add(ld);
            i++;
        }
        Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void getSongsFromDataBase() {

        List<StarredSong> starredSongList = helper.getAllStarredSongs();
        int i = 0;
        Collections.reverse(starredSongList);
        for (StarredSong song : starredSongList) {
            ListFragmentSongMusics.DataBean ld = new ListFragmentSongMusics.DataBean();
            ld.setId(song.getSongId());
            ld.setLrc(song.getLrc());
            ld.setName(song.getName());
            ld.setSinger(song.getSinger());
            ld.setPic(song.getPic());
            ld.setUrl(song.getUrl());
            ld.setNumber(String.valueOf(i + 1));
            ld.setTime(song.getTime());
            mData.add(ld);
            i++;
        }
        Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
            }
        });

    }

    private void sendSearchRequest() {
        mData.clear();
        for (int i = 1; i < 6; i++) {
            int finalI = i;
            Call client = HttpUtil.sendOkHttpRequest(FreeSongPath1 + SearchName + FreeSongPath3 + i + FreeSongPath4, new okhttp3.Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    checkSearchLast(SearchName, finalI);
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    String ListResponseData = null;//得到服务器返回的具体内容
                    if (response.body() != null) {
                        ListResponseData = response.body().string();
                    }
                    parseJSONWithSearchGSON(ListResponseData, finalI, SearchName);


                }
            });
            clientList.add(client);
        }

    }

    private void sendRequestWithOkHttp() {
        System.out.println("使用apirequest");
        Call client = HttpUtil.sendOkHttpRequest(GetFindSongsId, new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String ListResponseData = null;//得到服务器返回的具体内容
                if (response.body() != null) {
                    ListResponseData = response.body().string();
                }
                parseJSONWithGSON(ListResponseData);

            }
        });
        clientList.add(client);
    }

    public ListFragmentSongMusics parseJSONWithSearchGSON(String ListResponseData, int i, String searchName) {
        JSONObject jsonObject = null;
        try {

            jsonObject = new JSONObject(ListResponseData);
            int code = jsonObject.getInt("code");
            if (code == 200) {
                JSONObject dataObject = jsonObject.getJSONObject("data");
                String url = dataObject.getString("src");
                String pic = dataObject.getString("cover");
                String name = dataObject.getString("songname");
                String singer = dataObject.getString("name");
                String lrc = "https://www.hhlqilongzhu.cn/api/dg_geci.php?msg=" + name + " " + singer + "&n=1&type=2";
                ListFragmentSongMusics.DataBean ld = new ListFragmentSongMusics.DataBean();
                ld.setPic(pic);
                ld.setName(name);
                ld.setSinger(singer);
                ld.setNumber(i + "");
                ld.setId(String.valueOf(i));
                ld.setLrc(lrc);
                ld.setUrl(url);
                checkUrl(url, ld, 1);
            } else {
                checkSearchLast(searchName, i);
            }


        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    private void checkSearchLast(String searchName, int i) {
        System.out.println("使用最后一个api查找" + path_612_1 + searchName + FirstPath2 + i + FirstPath3);
        Call client = HttpUtil.sendOkHttpRequest(path_612_1 + searchName + FirstPath2 + i + FirstPath3, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                e.printStackTrace();
//                        Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response1) throws IOException {

                String ListResponseData = response1.body().string();//得到服务器返回的具体内容
                System.out.println();
                System.out.println("使用这个apill" + ListResponseData + "www" + ListResponseData.length());
                if (ListResponseData.startsWith("<html>") || ListResponseData.isEmpty()) {

                } else {
                    System.out.println("使用这个apiww" + ListResponseData);
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(ListResponseData);

                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            // 遍历歌曲列表
                            JSONObject dataObject = jsonObject;
                            String url = dataObject.getString("music_url");
                            String pic = dataObject.getString("cover");
                            String name = dataObject.getString("title");
                            String singer = dataObject.getString("singer");
                            String lrc = "https://www.hhlqilongzhu.cn/api/dg_geci.php?msg=" + name + " " + singer + "&n=1&type=2";
                            ListFragmentSongMusics.DataBean ld = new ListFragmentSongMusics.DataBean();
                            ld.setPic(pic);
                            ld.setName(name);
                            ld.setSinger(singer);
                            ld.setNumber(i + "");
                            ld.setId(String.valueOf(i));
                            ld.setLrc(lrc);
                            ld.setUrl(url);
                            checkUrl(url, ld, 2);
                        }


                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }

                }


            }


        });
        clientList.add(client);
    }


    public ListFragmentSongMusics parseJSONWithGSON(String jsonData) {

        mData.clear();
        try {
            JSONArray jsonArray = new JSONArray(jsonData);
//Log.d("ListFragment","Data共有多少条数据"+jsonArray.length());
            int length = Math.min(Max, jsonArray.length());
            for (int i = 0; i < length; i++) {
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                String pic = jsonObject1.getString("pic");
                String url = jsonObject1.getString("url");
                String name = jsonObject1.getString("name");
                String singer = jsonObject1.getString("artist");
//                String id = jsonObject1.getString("id");
                int number = i + 1;
//                long time=jsonObject1.getLong("time");
                //如果下面的api用不了了，可以用原来的网易的歌词
                // String lrc=jsonObject1.getString("lrc");
                String lrc = "https://www.hhlqilongzhu.cn/api/dg_geci.php?msg=" + name + " " + singer + "&n=1&type=2";
//                String url=jsonObject1.getString("url");
                Call client = HttpUtil.sendOkHttpRequest("https://jkyapi.top/API/hqyyid.php?name=" + name + " " + singer + "&type=qq&page=1&limit=1", new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        String id = null;
                        checkOther(name, singer, pic, lrc, number, id, url);
//                        Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response1) throws IOException {
                        String ListResponseData = response1.body().string();//得到服务器返回的具体内容

                        JSONArray dataArray = null;
                        try {
                            JSONObject jsonObject = new JSONObject(ListResponseData);
                            dataArray = jsonObject.getJSONArray("data");
                            JSONObject dataObject = dataArray.getJSONObject(0);
                            String id = dataObject.getString("id");
                            checkOther(name, singer, pic, lrc, number, id, url);
                        } catch (JSONException e) {
//                                    throw new RuntimeException(e);
                            String id = null;
                            checkOther(name, singer, pic, lrc, number, id, url);
                        }

                    }
                });
                clientList.add(client);
            }


        } catch (JSONException e) {
            e.printStackTrace();
//            Toast.makeText(getActivity(),"获取服务器数据失败",Toast.LENGTH_SHORT).show();
        }
        return null;
    }

    public static long[] res = new long[1];

    public void getSongs(String name, String singer, String pic, String lrc, int number, String id, String url) {
//        System.out.println();
        System.out.println("使用这个apikkk" + path_612_1 + name + " " + singer + FirstPath2 + "1" + FirstPath3);
        if (singer.length() > 5) {
            Call client = HttpUtil.sendOkHttpRequest(path_612_1 + name + FirstPath2 + "1" + FirstPath3, new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                    checkLast(name, singer, pic, lrc, number, id, url);
//                        Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(Call call, Response response1) throws IOException {

                    String ListResponseData = response1.body().string();//得到服务器返回的具体内容
                    System.out.println();
                    System.out.println("使用这个apill" + ListResponseData + "www" + ListResponseData.length());
                    if (ListResponseData.startsWith("<html>") || ListResponseData.isEmpty()) {
                        checkLast(name, singer, pic, lrc, number, id, url);
                    } else {
                        System.out.println("使用这个apiww" + ListResponseData);
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(ListResponseData);

                            int code = jsonObject.getInt("code");
                            if (code == 200) {
                                ListFragmentSongMusics.DataBean ld = new ListFragmentSongMusics.DataBean();
                                ld.setPic(pic);
                                ld.setName(name);
                                ld.setSinger(singer);
                                ld.setNumber(number + "");
                                ld.setId(id);
                                ld.setLrc(lrc);
                                String url = jsonObject.getString("music_url");
                                ld.setUrl(url);
                                checkUrl(url, ld, 2);
                            } else {
                                checkLast(name, singer, pic, lrc, number, id, url);
                            }

                        } catch (JSONException e) {
                            checkLast(name, singer, pic, lrc, number, id, url);
//                        throw new RuntimeException(e);
                        }

                    }


                }


            });
            clientList.add(client);
        } else {
            Call client = HttpUtil.sendOkHttpRequest(path_612_1 + name + " " + singer + FirstPath2 + "1" + FirstPath3, new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                    e.printStackTrace();
//                        Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(Call call, Response response1) throws IOException {

                    String ListResponseData = response1.body().string();//得到服务器返回的具体内容
                    System.out.println();
                    System.out.println("使用这个apill" + ListResponseData + "www" + ListResponseData.length());
                    if (ListResponseData.startsWith("<html>") || ListResponseData.isEmpty()) {
                        checkLast(name, singer, pic, lrc, number, id, url);
                    } else {
                        System.out.println("使用这个apiww" + ListResponseData);
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(ListResponseData);

                            int code = jsonObject.getInt("code");
                            if (code == 200) {
                                ListFragmentSongMusics.DataBean ld = new ListFragmentSongMusics.DataBean();
                                ld.setPic(pic);
                                ld.setName(name);
                                ld.setSinger(singer);
                                ld.setNumber(number + "");
                                ld.setId(id);
                                ld.setLrc(lrc);
                                String url = jsonObject.getString("music_url");
                                ld.setUrl(url);
                                checkUrl(url, ld, 2);
                            } else {
                                checkLast(name, singer, pic, lrc, number, id, url);
                            }

                        } catch (JSONException e) {
                            checkLast(name, singer, pic, lrc, number, id, url);
//                        throw new RuntimeException(e);
                        }

                    }


                }


            });
            clientList.add(client);
        }

    }

    private void checkLast(String name, String singer, String pic, String lrc, int number, String id, String url) {
        System.out.println("使用最后一个" + LastPath1 + name + " " + singer + LastPath2);
        Call client = HttpUtil.sendOkHttpRequest(LastPath1 + name + " " + singer + LastPath2, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                e.printStackTrace();
//                        Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response1) throws IOException {

                String ListResponseData = response1.body().string();//得到服务器返回的具体内容
                System.out.println();
                System.out.println("使用最后一个" + ListResponseData + "www" + ListResponseData.length());
                if (ListResponseData.startsWith("<html>") || ListResponseData.isEmpty()) {
                    //无法解析为json
                } else {
                    System.out.println("使用这个apiww" + ListResponseData);
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(ListResponseData);

                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            JSONObject resultObject = jsonObject.getJSONObject("result");
                            JSONArray songsArray = resultObject.getJSONArray("songs");
                            JSONObject songObject = songsArray.getJSONObject(0);
                            long sid = songObject.getInt("id");
                            System.out.println("获取歌曲id" + sid);
                            ListFragmentSongMusics.DataBean ld = new ListFragmentSongMusics.DataBean();
                            ld.setPic(pic);
                            ld.setName(name);
                            ld.setSinger(singer);
                            ld.setNumber(number + "");
                            ld.setId(id);
                            ld.setLrc(lrc);
                            String url = "http://music.163.com/song/media/outer/url?id=" + sid + ".mp3";
                            ld.setUrl(url);
                            checkUrl(url, ld, 3);
                        } else {
                            ListFragmentSongMusics.DataBean ld = new ListFragmentSongMusics.DataBean();
                            ld.setPic(pic);
                            ld.setName(name);
                            ld.setSinger(singer);
                            ld.setNumber(number + "");
                            ld.setId(id);
                            ld.setLrc(lrc);
                            ld.setUrl(url);
                            checkUrl(url, ld, 3);
                        }


                    } catch (JSONException e) {
                        ListFragmentSongMusics.DataBean ld = new ListFragmentSongMusics.DataBean();
                        ld.setPic(pic);
                        ld.setName(name);
                        ld.setSinger(singer);
                        ld.setNumber(number + "");
                        ld.setId(id);
                        ld.setLrc(lrc);
                        ld.setUrl(url);
                        checkUrl(url, ld, 3);
//                        throw new RuntimeException(e);
                    }

                }


            }


        });
        clientList.add(client);
    }

    public static long getMp3DurationFromUrl(String mp3Url) throws IOException, BitstreamException {

        HttpUtil.sendOkHttpRequest(mp3Url, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
//                        Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response1) throws IOException {
                if (!response1.isSuccessful())
                    throw new IOException("Unexpected code " + response1);

                try (BufferedInputStream bis = new BufferedInputStream(response1.body().byteStream())) {
                    Bitstream bt = new Bitstream(bis);
                    Header h = bt.readFrame();

                    res[0] = (long) h.total_ms((int) response1.body().contentLength());
                } catch (BitstreamException e) {
                    throw new RuntimeException(e);
                }
                String ListResponseData = response1.body().string();
            }
        });
        return 0;
    }


    public void checkOther(String name, String singer, String pic, String lrc, int number, String id, String url) {
        System.out.println("第一个api" + FreeSongPath1 + name + " " + singer + FreeSongPath2);
        Call client = HttpUtil.sendOkHttpRequest(FreeSongPath1 + name + " " + singer + FreeSongPath2, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                getSongs(name, singer, pic, lrc, number, id, url);
//                        Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String ListResponseData = response.body().string();//得到服务器返回的具体内容
                System.out.println("第一个api" + ListResponseData);
                JSONObject jsonObject = null;
                try {

                    jsonObject = new JSONObject(ListResponseData);
                    int code = jsonObject.getInt("code");
                    if (code == 200) {
                        JSONObject dataObject = jsonObject.getJSONObject("data");
                        String url = dataObject.getString("src");
                        ListFragmentSongMusics.DataBean ld = new ListFragmentSongMusics.DataBean();
                        ld.setPic(pic);
                        ld.setName(name);
                        ld.setSinger(singer);
                        ld.setNumber(number + "");
                        ld.setId(id);
                        ld.setLrc(lrc);
                        ld.setUrl(url);
                        checkUrl(url, ld, 1);

                    } else getSongs(name, singer, pic, lrc, number, id, url);

                } catch (JSONException e) {
                    getSongs(name, singer, pic, lrc, number, id, url);
//                    throw new RuntimeException(e);
                }
//                catch (BitstreamException e) {
//                    throw new RuntimeException(e);
//                }

            }
        });
        clientList.add(client);
    }

    private void checkUrl(final String url, ListFragmentSongMusics.DataBean ld, int now) {

        AsyncTask task =   new AsyncTask<Void, Void, returnFormat>() {
            @Override
            protected returnFormat doInBackground(Void... voids) {
                try {
                    URL urlObj = new URL(url);
                    HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
                    connection.setRequestMethod("GET");
                    int responseCode = connection.getResponseCode();
                    long contentLength = connection.getContentLength();
                    //可以请求
                    return new returnFormat(responseCode == HttpURLConnection.HTTP_OK, contentLength);
                } catch (Exception e) {
                    //请求失败
                    e.printStackTrace();
                    return null;
                }
            }

            @Override
            protected void onPostExecute(returnFormat isAvailable) {

                if (isAvailable != null) {
                    System.out.println("获取最终结果" + isAvailable.getLength() + " " + now);
                    //可以播放

                    //进行时间长度解析
                    if (isAvailable.getLength() > 0) {
                        // 假设音频编码的比特率为128 kbps
                        long bitrate = 128000; // 比特率（比特每秒）
                        // 计算时长（秒）= 文件大小（字节） / 比特率（比特每秒） / 8（将比特转换为字节）
                        long durationInSeconds = (isAvailable.getLength() * 8) / bitrate + 50;
                        System.out.println("时间长度 " + durationInSeconds + " seconds");
                        ld.setTime(230);
                        mData.add(ld);

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter.notifyDataSetChanged();
                            }
                        });
                    } else {
                        if (now == 1)
                            getSongs(ld.getName(), ld.getSinger(), ld.getPic(), ld.getLrc(), Integer.parseInt(ld.getNumber()), ld.getId(), ld.getUrl());
                        else if (now == 2)
                            checkLast(ld.getName(), ld.getSinger(), ld.getPic(), ld.getLrc(), Integer.parseInt(ld.getNumber()), ld.getId(), ld.getUrl());

                    }

                } else {
                    if (now == 1)
                        getSongs(ld.getName(), ld.getSinger(), ld.getPic(), ld.getLrc(), Integer.parseInt(ld.getNumber()), ld.getId(), ld.getUrl());
                    else if (now == 2)
                        checkLast(ld.getName(), ld.getSinger(), ld.getPic(), ld.getLrc(), Integer.parseInt(ld.getNumber()), ld.getId(), ld.getUrl());
                }
            }

        }.execute();
        tasks.add(task);


    }

    //主图图片和高斯背景图
    private void setPicture() {
        Glide.with(getActivity())
                .load(FindImgUrlPath)
                .override((int) CommonUtils.getDimens(R.dimen.dp_140), (int) CommonUtils.getDimens(R.dimen.dp_140))
                .into(binding.include.ivOnePhoto);

        // "14":模糊度；"3":图片缩放3倍后再进行模糊
        Glide.with(getActivity())
                .load(FindImgUrlPath)
                .error(R.mipmap.stackblur_default)
                .placeholder(R.mipmap.stackblur_default)
//                .crossFade(3000)//动画效果时长
                .dontAnimate()//取消动画效果
                .bitmapTransform(new BlurTransformation(getActivity(), 200, 3))// 设置高斯模糊
//                .bitmapTransform(new BlurTransformation(getActivity(), 14, 3))
                .into(binding.include.imgItemBg);
    }

    //接收FindFragment中RecyclerView的Item消息类
    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void messageEventBus(MessageEvent event) {
        binding.include.tvOneCity.setText(event.getFindGridItemName());
        if (event.getSongs() != null) {
            int i = 0;
            for (Song song : event.getSongs()) {
                ListFragmentSongMusics.DataBean ld = new ListFragmentSongMusics.DataBean();
                ld.setId(String.valueOf(i + 1));
                ld.setLrc(song.lrc);
                ld.setName(song.song);
                ld.setSinger(song.singer);
                ld.setPic(song.picPath);
                ld.setUrl(song.path);
                ld.setNumber(String.valueOf(i + 1));
                ld.setTime(song.duration);
                mData.add(ld);
                i++;
            }
            Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                @SuppressLint("NotifyDataSetChanged")
                @Override
                public void run() {
                    adapter.notifyDataSetChanged();
                }
            });
        }
    }


    // 设置RecyclerView
    private void setAdapter() {
        binding.tvTxt.setVisibility(View.GONE);
        binding.xrvList.setVisibility(View.VISIBLE);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.xrvList.setLayoutManager(mLayoutManager);
        binding.xrvList.setNestedScrollingEnabled(false);//需加，不然滑动不流畅
        binding.xrvList.setHasFixedSize(false);
        adapter = new ListRecAdapter(getActivity(), mData);
        binding.xrvList.setAdapter(adapter);

        // 设置item及item中控件的点击事件
        adapter.setOnItemClickListener(MyItemClickListener);
    }

    //item＋item里的控件点击监听事件
    private ListRecAdapter.OnItemClickListener MyItemClickListener = new ListRecAdapter.OnItemClickListener() {
        BottomSheetDialog bottomSheetDialog;

        @Override
        public void onItemClick(View v, ListRecAdapter.ViewName viewName, final int position) {
            String Pic = mData.get(position).getPic();
            String Name = mData.get(position).getName();
            String Singer = mData.get(position).getSinger();
            String Time = TimeUtil.formatSeconds(mData.get(position).getTime());
            String Lrc = mData.get(position).getLrc();
            String url = mData.get(position).getUrl();
            String songId = mData.get(position).getId();
            System.out.println("wwww" + songId + Name);

            //viewName可区分item及item内部控件
            switch (v.getId()) {
                case R.id.ListFragment_menu://子项菜单内容
//                  Toast.makeText(getActivity(),"你点击了同意按钮"+(position+1),Toast.LENGTH_SHORT).show();
                    View view = View.inflate(getActivity(), R.layout.list_dialog, null);
                    MyRoundedImageView localDialogIcon = view.findViewById(R.id.list_DialogIcon);//头部歌曲图片
                    Glide.with(getActivity()).load(Pic).into(localDialogIcon);
                    TextView dialog_song = view.findViewById(R.id.list_dialog_song);//头部歌名
                    dialog_song.setText(Name);
                    TextView dialog_singer = view.findViewById(R.id.list_dialog_singer);//头部歌手
                    dialog_singer.setText(Singer);
                    TextView dialog_singer2 = view.findViewById(R.id.list_dialog_singer2);//歌手
                    dialog_singer2.setText(Singer);
                    TextView dialog_album = view.findViewById(R.id.list_dialog_album);//专辑
                    dialog_album.setText(Name);
                    TextView dialog_time = view.findViewById(R.id.list_dialog_time);//歌曲时长
                    dialog_time.setText(Time);

                    RelativeLayout shareMusic = view.findViewById(R.id.shareMusic);//分享按钮事件
                    shareMusic.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent textIntent = new Intent(Intent.ACTION_SEND);
                            textIntent.setType("text/plain");
                            textIntent.putExtra(Intent.EXTRA_TEXT, "https://i.y.qq.com/n2/m/musiclite/playsong/index.html?app_type=qmlite&songmid=" + mData.get(position).getId());
                            startActivity(Intent.createChooser(textIntent, "分享"));
                        }
                    });
                    RelativeLayout NetToPlay = view.findViewById(R.id.NetToPlay);//到播放页事件
                    NetToPlay.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            viewPager.setCurrentItem(1);
                            bottomSheetDialog.hide();
                        }
                    });

                    // 下载音乐
                    RelativeLayout download = view.findViewById(R.id.download);
                    download.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            DownloadMusic downloadMusic = new DownloadMusic();
                            downloadMusic.name = Name.replace(":", "：");
                            downloadMusic.pic = Pic;
                            downloadMusic.singer = Singer.replace("/", "&");
                            downloadMusic.time = Time;
                            downloadMusic.lrc = Lrc;
                            downloadMusic.album = Name;
                            DownloadMusicUtils.downloadMusicMethod(url, Pic, downloadMusic);
                            System.out.println("下载图片" + Pic);
                            System.out.println("下载音乐" + url);
                            Toast.makeText(getActivity(), "已下载", Toast.LENGTH_SHORT).show();
                        }
                    });

                    bottomSheetDialog = new BottomSheetDialog(getActivity());
                    bottomSheetDialog.setContentView(view);
                    bottomSheetDialog.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//设置BottomSheetDialog圆角
                    bottomSheetDialog.show();
                    break;
                case R.id.ListintoPlayPage:
//                    Toast.makeText(getActivity(),"你点击了item按钮"+(position+1),Toast.LENGTH_SHORT).show();
//                  发送数据到播放页
                    Intent intent = new Intent(getActivity(), SongActivity.class);
                    EventBus.getDefault().postSticky(new ListToPlayEvent(Pic, Name, Singer, Lrc, url, Time, songId));
//                    viewPager.setCurrentItem(1);
                    getActivity().startActivity(intent);
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onItemLongClick(View v) {

        }
    };

    //toolbar设置
    private void setTitleBar() {
        ((AppCompatActivity) getActivity()).setSupportActionBar(binding.titleToolBar);

        ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        if (actionBar != null) {
            //去除默认Title显示
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.mipmap.back);
        }

        binding.titleToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();

            }
        });
    }


    //初始化滑动渐变
    private void initSlideShapeTheme() {

        setImgHeaderBg();

        // toolbar的高度
        int toolbarHeight = binding.titleToolBar.getLayoutParams().height;
        // toolbar+状态栏的高度
        final int headerBgHeight = toolbarHeight + StatusBarUtil.getStatusBarHeight(getActivity());

        // 使背景图向上移动到图片的最底端，保留toolbar+状态栏的高度
        binding.ivTitleHeadBg.setVisibility(View.VISIBLE);
        ViewGroup.LayoutParams params = binding.ivTitleHeadBg.getLayoutParams();
        ViewGroup.MarginLayoutParams ivTitleHeadBgParams = (ViewGroup.MarginLayoutParams) binding.ivTitleHeadBg.getLayoutParams();
        int marginTop = params.height - headerBgHeight;
        ivTitleHeadBgParams.setMargins(0, -marginTop, 0, 0);
        binding.ivTitleHeadBg.setImageAlpha(0);

        // 为头部是View的界面设置状态栏透明
        StatusBarUtil.setTranslucentImageHeader(getActivity(), 0, binding.titleToolBar);

        ViewGroup.LayoutParams imgItemBgparams = binding.include.imgItemBg.getLayoutParams();
        // 获得高斯图背景的高度
        imageBgHeight = imgItemBgparams.height;

        // 监听改变透明度
        initScrollViewListener();

    }


    //加载titlebar背景,加载后将背景设为透明
    private void setImgHeaderBg() {
        Glide.with(getActivity())
                .load(FindImgUrlPath)
//                .placeholder(R.mipmap.stackblur_default)
                .error(R.mipmap.stackblur_default)
                .bitmapTransform(new BlurTransformation(getActivity(), 200, 3))// 设置高斯模糊
                .listener(new RequestListener<String, GlideDrawable>() {//监听加载状态
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        binding.titleToolBar.setBackgroundColor(Color.TRANSPARENT);
                        binding.ivTitleHeadBg.setImageAlpha(0);
                        binding.ivTitleHeadBg.setVisibility(View.VISIBLE);
                        return false;
                    }
                }).into(binding.ivTitleHeadBg);
    }

    private void initScrollViewListener() {
        // 为了兼容api23以下
        binding.nsvScrollview.setOnMyScrollChangeListener(new MyNestedScrollView.ScrollInterface() {
            @Override
            public void onScrollChange(int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                scrollChangeHeader(scrollY);
            }
        });

        int titleBarAndStatusHeight = (int) (CommonUtils.getDimens(R.dimen.dp_58) + StatusBarUtil.getStatusBarHeight(getActivity()));
        slidingDistance = imageBgHeight - titleBarAndStatusHeight - (int) (CommonUtils.getDimens(R.dimen.dp_30));
    }

    //根据页面滑动距离改变Header透明度方法
    private void scrollChangeHeader(int scrolledY) {

//        DebugUtil.error("---scrolledY:  " + scrolledY);
//        DebugUtil.error("-----slidingDistance: " + slidingDistance);

        if (scrolledY < 0) {
            scrolledY = 0;
        }
        float alpha = Math.abs(scrolledY) * 1.0f / (slidingDistance);
        Drawable drawable = binding.ivTitleHeadBg.getDrawable();
//        DebugUtil.error("----alpha:  " + alpha);

        if (drawable != null) {
            if (scrolledY <= slidingDistance) {
                // title部分的渐变
                drawable.mutate().setAlpha((int) (alpha * 255));
                binding.ivTitleHeadBg.setImageDrawable(drawable);
            } else {
                drawable.mutate().setAlpha(255);
                binding.ivTitleHeadBg.setImageDrawable(drawable);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        binding.xrvList.setFocusable(false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);//反注册
    }

}

class returnFormat {
    boolean flag;
    long length;

    public returnFormat(boolean b, long contentLength) {
        flag = b;
        length = contentLength;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public long getLength() {
        return length;
    }

    public void setLength(long length) {
        this.length = length;
    }
}
